# This is a sample Python script.

# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.


# coding:utf-8

from PIL import Image, ImageDraw, ImageFont
import tkinter
from tkinter import filedialog
import os
import datetime  # 引入datetime模块

def ui_open_img():
    root = tkinter.Tk()  # 创建一个Tkinter.Tk()实例
    root.withdraw()  # 将Tkinter.Tk()实例隐藏
    default_dir = r"D:\ProjectX\01 RayFile\02 Test\ray_files"
    # file_path = tkinter.filedialog.askopenfilename(title=u'选择文件', initialdir=(os.path.expanduser(default_dir)))
    file = filedialog.askopenfilename(title=u'选择文件',
                                      filetypes=[('jpg', '*.jpg'), ('All Files', '*')],
                                      )
    print('Reading Ray File: ', file)
    return file

def add_text_to_image(image, text):
    font = ImageFont.truetype('C:\Windows\Fonts\STHUPO.TTF', 36)

    # 添加背景
    new_img = Image.new('RGBA', (image.size[0] * 3, image.size[1] * 3), (0, 0, 0, 0))
    new_img.paste(image, image.size)

    # 添加水印
    font_len = len(text)
    rgba_image = new_img.convert('RGBA')
    text_overlay = Image.new('RGBA', rgba_image.size, (255, 255, 255, 0))
    image_draw = ImageDraw.Draw(text_overlay)

    for i in range(0, rgba_image.size[0], font_len * 40 + 100):
        for j in range(0, rgba_image.size[1], 200):
            image_draw.text((i, j), text, font=font, fill=(0, 0, 0, 30))
    text_overlay = text_overlay.rotate(-45)
    image_with_text = Image.alpha_composite(rgba_image, text_overlay)

    # 裁切图片
    image_with_text = image_with_text.crop((image.size[0], image.size[1], image.size[0] * 2, image.size[1] * 2))
    return image_with_text


if __name__ == '__main__':
    img = Image.open(ui_open_img())
    im_after = add_text_to_image(img, u'瓜哥CAE')
    time_str = datetime.datetime.now().strftime('%Y-%m-%d_%H:%M:%S')  # 获取当前时间并转化成字符串
    im_after.save(u'瓜哥CAE.png')
